package com.zmj.framework.base.sql;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmj.framework.exception.business.BizException;
import com.zmj.framework.util.StringUtil;

import java.util.Map;

/**
 * @author scy
 * 查询条件构造器
 */
public class Condition {

	private static final String ORDER_BY = "createTime";
	private static final String ORDER = "DESC";
	private static final String ORDER_ASC = "ASC";
	private static final String SELECT = "SELECT";

	/**
	 * 转化成mybatis plus中的Page
	 * @param query
	 * @return
	 */
	public static <T> Page<T> getPage(Query query) {
		if(StrUtil.isBlank(query.getOrder())) {
			query.setOrder(ORDER);
		} else {
			if(!query.getOrder().toUpperCase().equals(ORDER)&&!query.getOrder().toUpperCase().equals(ORDER_ASC)) {
				throw new BizException("参数orderBy只能是DESC或ASC");
			}
		}
		if(StrUtil.isBlank(query.getOrderBy())) {
			query.setOrderBy(ORDER_BY);
		} else {
			if(query.getOrderBy().toUpperCase().contains(SELECT)) {
				throw new BizException("参数orderBy错误，不允许包含select语句");
			}
		}
		Page<T> page = new Page<>(Convert.toInt(query.getCurrent(), 1), Convert.toInt(query.getSize(), 10));
		if(ObjectUtil.isAllNotEmpty(query.getOrder(),query.getOrderBy()) && "ASC".equals(query.getOrder())) {
			page.addOrder(OrderItem.asc(StringUtil.humpToUnderline(query.getOrderBy())));
		}
		if(ObjectUtil.isAllNotEmpty(query.getOrder(),query.getOrderBy()) && "DESC".equals(query.getOrder())) {
			page.addOrder(OrderItem.desc(StringUtil.humpToUnderline(query.getOrderBy())));
		}
		return page;
	}

	/**
	 * 获取mybatis plus中的QueryWrapper
	 * @param entity
	 * @param <T>
	 * @return
	 */
	public static <T> QueryWrapper<T> getQueryWrapper(T entity) {
		return new QueryWrapper<>(entity);
	}

	/**
	 * 获取mybatis plus中的QueryWrapper
	 * @param query
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Class<T> clazz,String... alias) {
		query.remove("current");
		query.remove("size");
		query.remove("order");
		query.remove("orderBy");
		QueryWrapper<T> qw = new QueryWrapper<>();
		qw.setEntity(ReflectUtil.newInstance(clazz));
		if(ArrayUtil.isEmpty(alias)) {
			SqlKeyword.buildCondition(query, qw,null);
		} else {
			SqlKeyword.buildCondition(query, qw,alias[0]);
		}
		return qw;
	}

}
